using UnityEngine;
using System.Collections;

public class WeaponZoom : MonoBehaviour {
	public bool debug = false;
	public Camera buildCamera;
	
	private float currentZoom 	= 0.0f;
	private float maxZoom 		= 100.0f;
	public float minDelta		= 0.1f;
	//public float zoomSpeed		= 0.1f;
	
	public string axisZoom 		= "WeaponZoom";
	public string axisCamX		= "Mouse X";
	public string axisCamY		= "Mouse Y";
	
	public float sensitivityX = 15F;
	public float sensitivityY = 15F;

	public float minimumX = -360F;
	public float maximumX = 360F;

	public float minimumY = -60F;
	public float maximumY = 60F;
	
	private int scope	= 1;
	public float scopeZoom = 25f;
	
	public float weightFactor = 0.25f;

	float rotationY = 0F;
	
	// Update is called once per frame
	void Update () {
		if ((buildCamera == null || !buildCamera.enabled)) {
			float weight = 1.0f;
			
			if (this.transform.parent.GetComponent<RigidbodyFPSController>() != null) {
				scope = this.transform.parent.GetComponent<RigidbodyFPSController>().GetScope();
				weight = transform.parent.GetComponent<RigidbodyFPSController>().GetWeight();
			}
	
			float axis = Input.GetAxis(axisZoom);
			
			float weightF = 1.0f;
			
			if (weight == 0.0f) {
				Debug.LogError("Weight must not be 0 as it will result in a division by zero exception!!!");
			} else {
				weightF = (1.0f / Mathf.Max(1.0f, weight * weightFactor));
			}
			
			float rotationX = transform.localEulerAngles.y + Input.GetAxis(axisCamX) * (sensitivityX * weightF) * inverseZoomFactor();
				
			rotationY += Input.GetAxis(axisCamY) * (sensitivityY * weightF) * inverseZoomFactor();
			rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
			
			transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
			
			if (Mathf.Abs(axis) > minDelta) {
				if (axis > 0) axis = (axis - minDelta) * (axis - minDelta);
				else 		  axis = (axis + minDelta) * (axis - minDelta) * -1;
	
				//axis *= zoomSpeed;
				
				currentZoom = Mathf.Clamp(scope*scopeZoom*axis,0,maxZoom);
				/*currentZoom = Mathf.Max(0.0f,
					Mathf.Min(maxZoom,
						currentZoom + axis * inverseZoomFactor()
					)
				);*/
			}else
				currentZoom = 0;
			
			Camera cam;
			if ((cam = GetComponent<Camera>()) != null) {
				cam.fieldOfView = 60f - zoomFactor() * 59f;
			}
		}
	}
	
	private float inverseZoomFactor() {
		return 1.0f - zoomFactor();
	}
	
	private float zoomFactor() {
		return currentZoom / maxZoom;
	}
	
	void OnGUI(){
		if (debug){
			GUI.Label(new Rect(Screen.width/2-100,50,200,75),"axis = " + Input.GetAxis(axisZoom) + "\n zoom = " + currentZoom + "\n scopes = " + scope.ToString(),"box");
			
		}
	}
}
